package com.yj.lcj.config;

import com.alibaba.fastjson.JSONObject;
import com.yj.lcj.utils.TokenManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenManager tokenManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String,Object> tokenMap = new HashMap<>(2);
        String token = request.getHeader("token");
        try {
            if (token != null && tokenManager.validateToken(token)) {
                // Token验证通过，继续请求
                return true;
            }
        } catch (Exception e){

            tokenMap.put("msg","token无效");
        }
        tokenMap.put("code",302);
        tokenMap.put("msg","token无效");
        log.error("token不存在");
        JSONObject json = new JSONObject(tokenMap);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        //拦截不放行
        return false;
    }
}
